package com.nulldev.util.uri.yt;

import java.util.LinkedList;
import java.util.regex.Pattern;

import com.nulldev.util.math.MathUtil;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.Soup_imported.Jsoup;
import com.nulldev.util.uri.Soup_imported.nodes.Document;
import com.nulldev.util.uri.Soup_imported.nodes.Element;
import com.nulldev.util.uri.Soup_imported.select.Elements;
import com.nulldev.util.uri.yt.extraction.TrendingVideo;

public class TrendingExtractor {
	public static final String VIEWKEY = "watch?v";
	public static final String URL = "https://www.youtube.com/feed/trending";
	
	public static LinkedList<TrendingVideo> parse() throws Exception {
		final LinkedList<TrendingVideo> videos = new LinkedList<TrendingVideo>();
		final String pageData = URIUtil.downloadPage(URIUtil.safeCreate(URL));
		final Document doc = Jsoup.parse(pageData);
		
		Elements questions = doc.select("a[href]");
        int counter = 0;
        for (Element link: questions){
            if(link.attr("href").contains(VIEWKEY) && !link.attr("title").isEmpty()) {
            	final String title = link.attr("title").split("  - ")[0];
            	if (!title.contains("https://www.youtube.com/watch?v=") && !title.contains("http://www.youtube.com/watch?v=")) {
            		long length = -1;
                	try {
                		length = MathUtil.TimeToSeconds.parseTime(link.attr("title").split(": ")[1].replaceAll(Pattern.quote("."), ""));
                	}catch (Exception e) {}
                	String id = link.attr("href").substring(link.attr("href").indexOf("=") + 1);
                	if (id.contains("&list=")) {
                		id = id.split(Pattern.quote("&list="))[0];
                	}
                	videos.add(new TrendingVideo(id, title, "http://i.ytimg.com/vi/" + id + "/default.jpg", length));
            	}
                //System.out.println("Video# " + ++counter + " : " + link.attr("title") + " : " + link.attr("href").substring(link.attr("href").indexOf("=") + 1));
            }
        }
        return videos;
	}
}
